package com.example.peibei.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.dingtao.common.bean.RefreshResult;
import com.dingtao.common.bean.User;
import com.dingtao.common.core.DataCall;
import com.dingtao.common.core.WDActivity;
import com.dingtao.common.core.exception.ApiException;
import com.dingtao.common.util.SPUtils;
import com.dingtao.common.util.UIUtils;
import com.example.peibei.R;
import com.example.peibei.base.SpConstant;
import com.example.peibei.bean.SpUserInfoCall;
import com.example.peibei.service.presenter.ChangeBgPresenter;
import com.example.peibei.service.presenter.EditUserInfoPresenter;
import com.example.peibei.service.presenter.FollowUserPresenter;
import com.example.peibei.service.presenter.GetOtherUserInfoPresenter;
import com.example.peibei.service.presenter.OperateBLPresenter;
import com.example.peibei.service.presenter.UploadImagePresenter;
import com.example.peibei.service.presenter.UserInfoPresenter;
import com.example.peibei.ui.fragment.AuthenticationFragment;
import com.example.peibei.ui.fragment.MyDynamicFragment;
import com.example.peibei.ui.fragment.MySendBillFragment;
import com.example.peibei.ui.utils.LevelImage;
import com.example.peibei.ui.weight.CenterDialog;
import com.example.peibei.ui.weight.GlideEngine;
import com.flyco.tablayout.SlidingTabLayout;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;
import com.jaeger.library.StatusBarUtil;
import com.linxiao.framework.dialog.BottomDialog;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.tencent.imsdk.v2.V2TIMConversation;
import com.tencent.qcloud.tuicore.TUIConstants;
import com.tencent.qcloud.tuicore.TUICore;
import com.tencent.qcloud.tuikit.tuiconversation.bean.ConversationInfo;
import com.yxp.permission.util.lib.PermissionUtil;
import com.yxp.permission.util.lib.callback.PermissionResultCallBack;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class PersonInfoActivityTwo extends WDActivity {
    @BindView(R.id.slide_tablayout)
    SlidingTabLayout tabLayout;
    @BindView(R.id.viewpager)
    ViewPager viewpager;
    @BindView(R.id.iv_head)
    ImageView iv_head;
    @BindView(R.id.tv_nickname)
    TextView tv_nickname;
    @BindView(R.id.tv_id)
    TextView tv_id;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.tv_age)
    TextView tv_age;
    @BindView(R.id.tv_height)
    TextView tv_height;
    @BindView(R.id.tv_favorites)
    TextView tv_favorites;
    @BindView(R.id.tv_follow)
    TextView tv_follow;
    @BindView(R.id.sign)
    TextView sign;
    @BindView(R.id.tv_gender)
    TextView tv_gender;
    @BindView(R.id.ll_no_follow)
    LinearLayout ll_no_follow;
    @BindView(R.id.ll_followed)
    LinearLayout ll_followed;
    @BindView(R.id.iv_edit)
    ImageView iv_edit;
    @BindView(R.id.ll_chat)
    LinearLayout ll_chat;
    @BindView(R.id.iv_image)
    ImageView ivBg;
    @BindView(R.id.iv_alpha)
    View iv_alpha;
    @BindView(R.id.fl_follow)
    FrameLayout fl_follow;

    private String[] title = {"动态", "技能", "认证"};
    private ArrayList<Fragment> fragments = new ArrayList<>();
    private GetOtherUserInfoPresenter getOtherUserInfoPresenter;
    private FollowUserPresenter followUserPresenter;
    private OperateBLPresenter operateBLPresenter;
    private UploadImagePresenter uploadImagePresenter;
    private ChangeBgPresenter changeBgPresenter;
    private UserInfoPresenter userInfoPresenter;
    private SPUtils spUtils;
    private String token;
    private String mid;
    private String mymid;
    private int follow;
    private boolean blackList;
    private String nickName;
    private int update_image_type;
    private EditUserInfoPresenter editUserInfoPresenter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_person_info_two;
    }

    @Override
    protected void initView() {
        ImmersionBar.with(this)
                .fitsSystemWindows(false)
                .statusBarDarkFont(false)
                .hideBar(BarHide.FLAG_HIDE_STATUS_BAR)
                .init();
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        Uri data = intent.getData();
        if (bundle!=null){
            mid = bundle.getString("mid");
        }else{
            if (data!=null){
                mid =  data.getQueryParameter("mid");
            }
        }

        spUtils = new SPUtils(this, SpConstant.USER_TOKEN);
        token = spUtils.getString(SpConstant.USER_TOKEN);
        mymid = spUtils.getLong(SpConstant.USER_MID) + "";
        getOtherUserInfoPresenter = new GetOtherUserInfoPresenter(new UserInfoCall());
        followUserPresenter = new FollowUserPresenter(new FollowUserCall());
        operateBLPresenter = new OperateBLPresenter(new OperaBlCall());
        uploadImagePresenter = new UploadImagePresenter(new UploadCall());
        editUserInfoPresenter = new EditUserInfoPresenter(new EditUserInfoCall());
        changeBgPresenter = new ChangeBgPresenter(new ChangeBgCall());
        userInfoPresenter = new UserInfoPresenter(new UserInfoCall());
        fragments.add(new MyDynamicFragment(mid));
        fragments.add(new MySendBillFragment(mid));
        fragments.add(new AuthenticationFragment(mid));
        viewpager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return title[position];
            }
        });
        tabLayout.setViewPager(viewpager, title, this, fragments);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getOtherUserInfoPresenter.reqeust(mid, mymid);

        if (mymid.equals(mid)) {
            userInfoPresenter.reqeust("Bearer " + token);
        }
    }

    @OnClick(R.id.tv_guanzhu)
    public void myFollow() {
        if (TextUtils.isEmpty(token)) {
            intent(LoginActivity.class);
            return;
        }
        if (mymid.equals(mid)) {
            intent(MyFollowListActivity.class);
        }
    }

    @OnClick(R.id.tv_fans)
    public void myFans() {
        if (TextUtils.isEmpty(token)) {
            intent(LoginActivity.class);
            return;
        }
        if (mymid.equals(mid)) {
            intent(MyFansListActivity.class);
        }
    }

    @OnClick(R.id.iv_edit)
    public void editUserInfo() {
        if (TextUtils.isEmpty(token)) {
            intent(LoginActivity.class);
            return;
        }
        if (mymid.equals(mid)) {
            intent(EditInfoActivity.class);
        } else {
            showDialog();
        }
    }

    @OnClick(R.id.iv_head)
    public void editHead() {
        if (TextUtils.isEmpty(token)) {
            intent(LoginActivity.class);
            return;
        }
        if (mymid.equals(mid)) {
            getPermission(1);
        }
    }

    @OnClick(R.id.iv_back)
    public void back() {
        finish();
    }

    @OnClick(R.id.ll_chat)
    public void chat() {
        ConversationInfo conversationInfo = new ConversationInfo();
        conversationInfo.setType(ConversationInfo.TYPE_CUSTOM);
        conversationInfo.setId(mid);
        conversationInfo.setGroup(false);
        conversationInfo.setTitle(nickName);
        startChatActivity(conversationInfo);
    }

    @OnClick(R.id.ll_no_follow)
    public void follow() {
        followUserPresenter.reqeust(1, "Bearer " + token, mid);
    }

    @OnClick(R.id.ll_followed)
    public void cancelFollow() {
        followUserPresenter.reqeust(0, "Bearer " + token, mid);
    }

    boolean isFollower = false;

    private void showOperBlDialog() {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_center_view, null);
        CenterDialog bottomDialog = new CenterDialog(this);
        bottomDialog.setContentView(dialogView);
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.show();

        TextView tv_cancel = dialogView.findViewById(R.id.tv_cancel);
        TextView tv_sure = dialogView.findViewById(R.id.tv_sure);
        TextView tv_title = dialogView.findViewById(R.id.tv_title);
        tv_title.setText("拉黑后，你将不再收到对方消息，并且你们互相看不到对方的发单和动态信息");
        tv_cancel.setOnClickListener(v -> bottomDialog.dismiss());
        tv_sure.setOnClickListener(v -> {
            operateBLPresenter.reqeust("Bearer " + token, Long.parseLong(mid), blackList ? 0 : 1);
            bottomDialog.dismiss();
        });
    }

    private void showDialog() {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_report, null);
        BottomDialog bottomDialog = new BottomDialog(this);
        bottomDialog.setContentView(dialogView);
        bottomDialog.setCanceledOnTouchOutside(true);
//        bottomDialog.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
        bottomDialog.show();
        TextView tv_cancel = dialogView.findViewById(R.id.tv_cancel);
        TextView tv_lahei = dialogView.findViewById(R.id.tv_lahei);
        LinearLayout ll_copy = dialogView.findViewById(R.id.ll_copy);
        LinearLayout ll_jubao = dialogView.findViewById(R.id.ll_jubao);
        LinearLayout ll_lahei = dialogView.findViewById(R.id.ll_lahei);
        tv_cancel.setOnClickListener(v -> bottomDialog.dismiss());
        if (!blackList) {
            tv_lahei.setText("拉黑");
        } else {
            tv_lahei.setText("取消拉黑");
        }
        ll_copy.setOnClickListener(v -> {
            ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("simple text", "wwww.qudan.com");
            clipboard.setPrimaryClip(clip);
            UIUtils.showToastSafe("链接已复制到剪贴板");
        });
        ll_jubao.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putString("mid", mid);
            intent(ReportActivity.class, bundle);
            bottomDialog.dismiss();
        });
        ll_lahei.setOnClickListener(v -> {
            if (blackList) {
                operateBLPresenter.reqeust("Bearer " + token, Long.parseLong(mid), blackList ? 0 : 1);
            } else {
                showOperBlDialog();
            }
            bottomDialog.dismiss();
        });
    }

    private void startChatActivity(ConversationInfo conversationInfo) {
        Bundle param = new Bundle();
        param.putInt(TUIConstants.TUIChat.CHAT_TYPE, conversationInfo.isGroup() ? V2TIMConversation.V2TIM_GROUP : V2TIMConversation.V2TIM_C2C);
        param.putString(TUIConstants.TUIChat.CHAT_ID, conversationInfo.getId());
        param.putString(TUIConstants.TUIChat.CHAT_NAME, conversationInfo.getTitle());
        if (conversationInfo.getDraft() != null) {
            param.putString(TUIConstants.TUIChat.DRAFT_TEXT, conversationInfo.getDraft().getDraftText());
            param.putLong(TUIConstants.TUIChat.DRAFT_TIME, conversationInfo.getDraft().getDraftTime());
        }
        param.putBoolean(TUIConstants.TUIChat.IS_TOP_CHAT, conversationInfo.isTop());

        if (conversationInfo.isGroup()) {
            param.putString(TUIConstants.TUIChat.FACE_URL, conversationInfo.getIconPath());
            param.putString(TUIConstants.TUIChat.GROUP_TYPE, conversationInfo.getGroupType());
        }
        if (conversationInfo.isGroup()) {
            TUICore.startActivity(TUIConstants.TUIChat.GROUP_CHAT_ACTIVITY_NAME, param);
        } else {
            TUICore.startActivity(TUIConstants.TUIChat.C2C_CHAT_ACTIVITY_NAME, param);
        }
    }


    @OnClick(R.id.iv_image)
    public void backgroundImage() {
        if (mymid.equals(mid)) {
//            if (vip){
                getPermission(2);
//            }else {
//                intent(MemberActivity.class);
//            }
        }
    }

    private static String[] PERMISSIONS = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private void getPermission(int type) {
        update_image_type = type;
        PermissionUtil.getInstance().request(this, PERMISSIONS,
                new PermissionResultCallBack() {
                    @Override
                    public void onPermissionGranted() {
                        showAlbum();
                    }

                    @Override
                    public void onPermissionGranted(String... strings) {
                        // 当所有权限的申请被用户同意之后,该方法会被调用
                        //get_NovelUrl(id);
                    }

                    @Override
                    public void onPermissionDenied(String... permissions) {

                        UIUtils.showToastSafe("部分权限被禁止需要手动开启");

                        // 当权限申请中的某一个或多个权限,被用户曾经否定了,并确认了不再提醒时,也就是权限的申请窗口不能再弹出时,该方法将会被调用
                        getPermission(type);
                    }

                    @Override
                    public void onRationalShow(String... permissions) {
                        UIUtils.showToastSafe("部分权限被禁止需要手动开启");
                        // 当权限申请中的某一个或多个权限,被用户否定了,但没有确认不再提醒时,也就是权限窗口申请时,但被否定了之后,该方法将会被调用.
                        getPermission(type);
                    }

                });
    }

    private void showAlbum() {
        com.luck.picture.lib.PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .maxSelectNum(1)
                .minSelectNum(1)
                .compress(true)
                .selectionMode(PictureConfig.SINGLE)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /*结果回调*/
        if (requestCode == PictureConfig.CHOOSE_REQUEST) {
            if (data != null) {
                List<LocalMedia> localMedia = com.luck.picture.lib.PictureSelector.obtainMultipleResult(data);
//                Bitmap bitmap = BitmapFactory.decodeFile(localMedia.get(0).getCompressPath());
//                ivBg.setImageBitmap(bitmap);
                ivBg.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (update_image_type == 2){
                            Glide.with(PersonInfoActivityTwo.this).load(localMedia.get(0).getCompressPath()).into(ivBg);
                        }else {
                            Glide.with(PersonInfoActivityTwo.this).load(localMedia.get(0).getCompressPath()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(iv_head);
//                            Glide.with(PersonInfoActivityTwo.this).load(localMedia.get(0).getCompressPath()).into(iv_head);
                        }
                    }
                },100);
                uploadImagePresenter.reqeust(localMedia.get(0).getCompressPath(),"Bearer " + token);
            }
        }

    }

    class EditUserInfoCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            UIUtils.showToastSafe("保存成功");
//            finish();
        }

        @Override
        public void fail(ApiException e, Object... args) {
        }
    }

    class ChangeBgCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            Log.i("answer", "修改成功：" + data);


        }

        @Override
        public void fail(ApiException e, Object... args) {
        }
    }


    class UploadCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            Log.i("answer", "图片上传成功：" + data);
            if (update_image_type == 2){
                changeBgPresenter.reqeust("Bearer " + token,data);
            }else {

                editUserInfoPresenter.reqeust("Bearer " + token, null, null, null, null, null, data, null, null, null);
            }
//            Glide.with(PersonInfoActivityTwo.this).load(data).into(ivBg);
        }

        @Override
        public void fail(ApiException e, Object... args) {
        }
    }

    class UserInfoCall extends SpUserInfoCall {

        @Override
        public void success(User data, Object... args) {
            super.success(data,args);

            nickName = data.getNickName();
            tv_nickname.setText(data.getNickName());
            tv_id.setText("id:" + data.getAutoId());
            tv_favorites.setText(data.getFavorites() + "");
            tv_follow.setText(data.getFollower() + "");
            blackList = data.isBlackList();
            tv_gender.setText(data.getGender() == 0 ? "女" : "男");
            if (!TextUtils.isEmpty(data.getYear())) {
                tv_age.setText(data.getYear());
            } else {
                tv_age.setVisibility(View.GONE);
            }
            if (!TextUtils.isEmpty(data.getArea())) {
                tv_address.setText(data.getArea());
            } else {
                tv_address.setVisibility(View.GONE);
            }
            if (!TextUtils.isEmpty(data.getJob())) {
                tv_height.setText(data.getJob());
            } else {
                tv_height.setVisibility(View.GONE);
            }
            if (mymid.equals(mid)) {
                ll_no_follow.setVisibility(View.GONE);
                ll_followed.setVisibility(View.GONE);
                fl_follow.setVisibility(View.GONE);
                ll_chat.setVisibility(View.GONE);
            } else {
                fl_follow.setVisibility(View.VISIBLE);
                ll_chat.setVisibility(View.GONE);
                isFollower = data.isFollow();
                if (isFollower) {
                    ll_followed.setVisibility(View.VISIBLE);
                    ll_no_follow.setVisibility(View.GONE);
                } else {
                    ll_followed.setVisibility(View.GONE);
                    ll_no_follow.setVisibility(View.VISIBLE);
                }
            }
            if (!TextUtils.isEmpty(data.getHomeBackground())){
                Glide.with(PersonInfoActivityTwo.this).load(data.getHomeBackground()).into(ivBg);
//                iv_alpha.setVisibility(View.VISIBLE);
//                iv_alpha.setAlpha(0.7f);
//            }else {
//                iv_alpha.setAlpha(0.4f);
            }
            Glide.with(PersonInfoActivityTwo.this).load(data.getImgUrl()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(iv_head);
//            if (!TextUtils.isEmpty(data.getImgUrl())) {
//                Glide.with(PersonInfoActivityTwo.this).load(data.getImgUrl()).into(ivBg);
//            }
            if (TextUtils.isEmpty(data.getSign())) {
                sign.setText("这家伙很神秘，没有输入个人简介...");
            } else {
                sign.setText(data.getSign());
            }
        }

        @Override
        public void fail(ApiException e, Object... args) {

        }
    }

    public static void LoadImgToBackground(Activity activity, Object img, final View view) {

    }

    class FollowUserCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            //还需要刷新处理
            getOtherUserInfoPresenter.reqeust(mid, mymid);
        }

        @Override
        public void fail(ApiException e, Object... args) {
            EventBus.getDefault().post(RefreshResult.getInstance(true, true));
        }
    }

    class OperaBlCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            if (blackList) {
                UIUtils.showToastSafe("已取消黑名单");
            } else {
                UIUtils.showToastSafe("已加入黑名单");
            }
            //还需要刷新处理
            getOtherUserInfoPresenter.reqeust(mid, mymid);
        }

        @Override
        public void fail(ApiException e, Object... args) {
            EventBus.getDefault().post(RefreshResult.getInstance(true, true));
        }
    }

    @Override
    protected void destoryData() {

    }
}
